package com.songsong.myblog2.controller;


import com.alibaba.fastjson.JSON;
import com.songsong.myblog2.domain.User;
import com.songsong.myblog2.domain.UserImage;
import com.songsong.myblog2.service.UserService;
import com.songsong.myblog2.util.FileUtil;
import com.songsong.myblog2.util.SignUpHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Administrator on 2018/12/24 0024.
 */
@Controller
public class UserController {

    /*注入service*/
    @Autowired
    private UserService userService;
    /*注入加密工具类*/
    @Autowired
    private SignUpHelper signUpHelper;

    /**
     * 用户注册
     */
    @RequestMapping("/register")
    @ResponseBody
    public String register(User user, HttpServletRequest request) {

        String authCode = request.getParameter("authCode");

        String trueMsgCode = (String) request.getSession().getAttribute("trueMsgCode");
        String msgCodePhone = (String) request.getSession().getAttribute("msgCodePhone");

        //判断验证码是否正确
        if (!authCode.equals(trueMsgCode)) {
            return "0";
        }
        if (!msgCodePhone.equals(user.getUsername())) {
            return "5";
        }
        //判断用户名是否存在

        /*调用方法加密密码*/
        signUpHelper.encryptPassword(user);
        return userService.addUser(user);

    }

    @RequestMapping("/getUserImage")
    @ResponseBody
    public String getUserImage() {
        /*获取用户手机号*/
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        List<UserImage> userImage = userService.getUserImage(username);
        String list = JSON.toJSONString(userImage);
        return list;
    }

    /**
     * 批量删除用户图片
     *
     * @param userImageUrl
     * @param userImageId
     * @return
     */
    @RequestMapping("/deleteUserImage")
    @ResponseBody
    public String deleteUserImage(String userImageUrl, String userImageId) {
        //这里接收的是json数组 需要解析
        JSONArray imageUrl = JSONArray.fromObject(userImageUrl);
        /*调用url处理方法*/
        FileUtil fileUtil = new FileUtil();
        List<String> image = fileUtil.changeImageUrl(imageUrl);
        //调用批量删除oss方法
        //调用方法 将oss服务器上的文件删除
        fileUtil.deleteOssFileMany(image);
        JSONArray imageId = JSONArray.fromObject(userImageId);
        //调用方法将数据库中对应的数据删除
        //将imageid封装成数据库中想要的数据
        Object[] objects = imageId.toArray();
        userService.deleteUserImage(objects);
        return "删除成功";
    }

    /**
     * 删除单个图片
     */
    @RequestMapping("/deleteUserImageAlone")
    @ResponseBody
    public String deleteUserImageAlone(String userImageUrl, String userImageId) {
        System.out.println(userImageId);
        System.out.println(userImageUrl);
        //1.处理url 删除oss服务器上的图片
        userImageUrl = userImageUrl.split("com/")[1];
        FileUtil fileUtil = new FileUtil();
        fileUtil.deleteOssFile(userImageUrl);
        //2.根据id删除数据库中的记录
        userService.deleteUserImageAlone(userImageId);
        return "删除成功";
    }

    /**
     * 获取用户头像
     *
     * @return
     */
    @RequestMapping("/getHeadPortraitUrl")
    @ResponseBody
    public String getHeadPortraitUrl() {
        /*获取用户手机号*/
        String userphone = (String) SecurityUtils.getSubject().getPrincipal();
        //找到用户头像url 返回数据
        return userService.getUserPhoto(userphone);
    }

    /**
     * 获得个人资料
     */
    @GetMapping("/getUserPersonalInfo")
    @ResponseBody
    public JSONObject getUserPersonalInfo() {
        /*获取用户手机号*/
        String userphone = (String) SecurityUtils.getSubject().getPrincipal();
        return userService.getUserPersonalInfoByUsername(userphone);
    }


    /**
     * 保存个人资料
     */
    @PostMapping("/savePersonalDate")
    @ResponseBody
    public JSONObject savePersonalDate(User user) {
        /*获取用户手机号*/
        String userphone = (String) SecurityUtils.getSubject().getPrincipal();
        user.setUsername(userphone);
        return userService.savePersonalDate(user);
    }

    /**
     * 用户修改为管理员
     *
     * @param userPhone
     * @return
     */
    @RequestMapping("/userToAdmin/{userPhone}")
    @RequiresRoles(value = "admin")
    public String updateUserToAdmin(@PathVariable("userPhone") String userPhone) {
        //调用service
        userService.updateUserToAdmin(userPhone);
        return "anon/superadmin";
    }

    /**
     * 管理员改为用户
     *
     * @param userPhone
     * @return
     */
    @RequestMapping("/adminToUser/{userPhone}")
    @RequiresRoles(value = "admin")
    public String updateAdminToUser(@PathVariable("userPhone") String userPhone) {
        //调用service
        userService.updateAdminToUser(userPhone);
        return "anon/superadmin";
    }

    /**
     * 删除用户
     *
     * @param userPhone
     * @return
     */
    @RequestMapping("/deleteUser/{userPhone}")
    @RequiresRoles(value = "admin")
    public String deleteUser(@PathVariable("userPhone") String userPhone) {
        //调用service
        userService.deleteUser(userPhone);
        return "anon/superadmin";
    }

    /**
     * 修改密码
     * @param phone
     * @param authCode
     * @param newPassword
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/changePassword")
    public String changePassword(@RequestParam("phone") String phone,
                                 @RequestParam("authCode") String authCode,
                                 @RequestParam("newPassword") String newPassword,
                                 HttpServletRequest request){

        String trueMsgCode = (String) request.getSession().getAttribute("trueMsgCode");
        String msgCodePhone = (String) request.getSession().getAttribute("msgCodePhone");

        //判断验证码是否正确
        if(!authCode.equals(trueMsgCode)){
            return "0";
        }
        //判断获得的手机号是否是发送验证码的手机号
        if(!phone.equals(msgCodePhone)){
            return "3";
        }
        User user = userService.findUser(phone);
        if(user == null){
            return "2";
        }
        /*调用方法加密密码*/
        user.setPassword(newPassword);
        signUpHelper.encryptPassword(user);
        userService.updatePasswordByPhone(phone, user.getPassword(),user.getSalt());

        return "1";
    }
}
